<?php

namespace app\admin\controller\works;

use app\common\controller\Backend;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Exception;
use think\Db;
use OSS\OssClient;
/**
 * 作品
 *
 * @icon fa fa-circle-o
 */
class Catalog extends Backend
{

    /**
     * Catalog模型对象
     * @var \app\admin\model\works\Catalog
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\WorksCatalog;

    }

    public function index(){
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model->with(['order'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
            foreach ($list->items() as $key => &$value) {
                $value['imagecount'] = Db::name('WorksPhoto')->where('works_catalog_id',$value['id'])->count('id') ?:0;
            }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $order = Db::name('shoproOrder')->where('order_sn',$params['order_sn'])->find();
        if(empty($order)){
            $this->error('订单号错误，没有当前订单');
        }
        $catalog = Db::name('WorksCatalog')->where('order_id',$order['id'])->find();
        if(!empty($catalog)){
            $this->error('订单号已经关联作品');
        }
        $result = false;
        Db::startTrans();
        try {
            $orderItem = Db::name('shopOrderItem')->alias('i')->join('__SHOPRO_GOODS__ g','g.id= i.goods_id')->where('i.order_id',$order['id'])->field('i.goods_id,i.order_id,i.user_id,g.formwork_id');
            $formwork = Db::name('Formwork')->where('id',$orderItem['formwork_id'])->find();
            $orderItem['title'] = $formwork['title'];
            $orderItem['description'] = $formwork['title'];
            $orderItem['category_id'] = $formwork['category_id'];
            $result = $this->model->allowField(true)->save($orderItem);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $params = $this->preExcludeFields($params);
        if(!empty($params)){
            $images = explode(',',$params['images']);
            $count = Db::name('WorksPhoto')->where('works_catalog_id',$row['id'])->max('weigh')?:0;
            $worksphoto=[];
            foreach ($images as $key => $value) {
                $worksphoto[]=[
                    'works_catalog_id'=>$row['id'],
                    'image'=>$value,
                    'weigh'=>$count+$key+1,
                    'createtime'=>time(),
                    'updatetime'=>time()
                ];
            }
        }
        $result = false;
        Db::startTrans();
        try {
            
            $result = Db::name('WorksPhoto')->insertAll($worksphoto);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function download($ids=null){
	    $picArr = Db::name('WorksPhoto')->where('works_catalog_id',$ids)->order('weigh esc')->select();
        if(empty($picArr)){
            $this->error('无图片文件');
        }
        $tmpDir = ROOT_PATH.'public/upload'; // 类似于/www/public/upload/
        $config = get_addon_config('alioss');
        $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);

        if (!file_exists($tmpDir)) {
            //创建文件夹
            mkdir($tmpDir, 0777, true);
        }

        $zipName = date('His') . mt_rand(1000, 9999) . '.zip'; // 压缩包文件名
        $zipNameUrl = $tmpDir .DS. $zipName; // 文件路径
        // 生成文件
        $zip = new \ZipArchive();
        if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) {
            //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
            if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) {
                // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
                return  '下载失败，文件夹不存在';
            }
            
        }
        foreach ($picArr as $key => $value) {
            //判断图片是否存在
            $isFile = $this->checkFileExists(cdnurl($value['image']));
            if (!$isFile) {
                continue;
            }
            $objectName = substr($value['image'],1);
	        
            $object = $ossClient->getObject($config['bucket'], $objectName);
            //添加图片
            $zip->addFromString($value['weigh'].'-'.basename($value['image']), $object);
        }
        // 关闭
        $zip->close();

        //没有文件
        if (!file_exists($zipNameUrl)) {
            return '下载失败，图片不存在或无法下载';
        }

        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . $zipName); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: ' . filesize($zipNameUrl)); //告诉浏览器，文件大小

        // 下面2步必须要
        ob_clean();
        flush();

        @readfile($zipNameUrl);
        unlink($zipNameUrl); // 删除文件
        exit;

    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function upload($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {

            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $params = $this->preExcludeFields($params);
        if(!empty($params)){
            $images = explode(',',$params['images']);
            $count = Db::name('WorksFormwork')->where('works_catalog_id',$row['id'])->max('weigh')?:0;
            $worksphoto=[];
            foreach ($images as $key => $value) {
                $worksphoto[]=[
                    'works_catalog_id'=>$row['id'],
                    'image'=>$value,
                    'weigh'=>$count+$key+1,
                    'createtime'=>time(),
                    'updatetime'=>time()
                ];
            }
        }
        $result = false;
        Db::startTrans();
        try {
            
            $result = Db::name('WorksFormwork')->insertAll($worksphoto);
            $row->is_finish = 2;
            $row->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 判断文件是否存在，支持本地及远程文件
     * @param String $file 文件路径
     * @return Boolean
     */
    private function checkFileExists($file)
    {
        // 远程文件
        if (strtolower(substr($file, 0, 5)) == 'https') {
            // 远程文件
            $header = get_headers($file, true);
            return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));

        } elseif (strtolower(substr($file, 0, 4)) == 'http') {
            // 远程文件
            $header = get_headers($file, true);
            return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
        } else {
            // 本地文件
            return file_exists($file);
        }
    }
}
